import {
  webSocketUrl
} from '@/utils/global'

let websock = null;
let global_callback = function (result) {
    if(result.code !== 200) {
        alert(result.msg);
    }
};

export function initWebSocket(userAppId) { //初始化weosocket
  websock = new WebSocket(webSocketUrl + "/" + userAppId);

  websock.onmessage = wsOnMessage;

  websock.onclose = wsClose;

  websock.onopen = wsOpen;

  websock.onerror = wsError;
}

// 实际调用的方法
export function sendMessage(agentData, callback) {
  if (callback) {
    global_callback = callback;
  }
  if (websock.readyState === websock.OPEN) {
    //若是ws开启状态
    wsSend(agentData)
  } else if (websock.readyState === websock.CONNECTING) {
    // 若是 正在开启状态，则等待1s后重新调用
    setTimeout(function () {
      sendMessage(agentData, callback);
    }, 1000);
  } else {
    // 若未开启 ，则等待1s后重新调用
    setTimeout(function () {
      sendMessage(agentData, callback);
    }, 1000);
  }
}

//连接建立成功会掉
function wsOpen(event) {
  console.log("连接成功");
}

//数据接收回调
function wsOnMessage(event) {
  if (global_callback) {
    global_callback(JSON.parse(event.data));
  }
}

//连接关闭回调
function wsClose(event) {
  alert("连接已关闭，code：" + event.code);
}

//发送消息
function wsSend(agentData) {
  websock.send(JSON.stringify(agentData));
}

//连接错误回调
function wsError() {
  alert("应用连接异常，请重新打开应用");
  closeWebSocket();
}

//关闭WebSocket连接
function closeWebSocket() {
  websocket.close();
}

//监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
window.onbeforeunload = function () {
  closeWebSocket();
}

/*关闭当前页*/
function closeCurrentPage() {
  var userAgent = navigator.userAgent;
  if (userAgent.indexOf("Firefox") != -1 || userAgent.indexOf("Chrome") != -1) {
    window.location.href = "about:blank";
    window.close();
  } else {
    window.opener = null;
    window.open("", "_self");
    window.close();
  }
}
